package com.manlitech.elkboot.utils.es;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * ES监控告警
 * @author Administrator
 * Date:  2021/1/5
 */

@Component
@Slf4j
public class EsAlert {

    @Autowired
    ESUtil esUtil;

    @Autowired
    RestTemplate restTemplate;

    /**
     * 每秒有错误则钉钉告警
     * @param indexName
     */
    public void everySecondIsErrorToDingDing(String indexName){
        List<Map<String, Object>> list = new ArrayList<>();
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        String[] fields = {"timestamp", "level", "message", "_id"};
        //需要返回和不返回的字段，可以是数组也可以是字符串
        sourceBuilder.fetchSource(fields, null);
        //设置根据哪个字段进行排序查询
        sourceBuilder.sort(new FieldSortBuilder("timestamp").order(SortOrder.DESC));

        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        //添加查询条件
        builder.must(QueryBuilders.matchQuery("level", "ERROR"));
        //设定时间
        Calendar cal= Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.HOUR_OF_DAY,8);
        cal.add(Calendar.MINUTE,-5);
        RangeQueryBuilder rangequerybuilder = QueryBuilders
                .rangeQuery("timestamp")
                .gte(cal.getTime());
        builder.filter(rangequerybuilder);

        list = ESUtil.SearchDataPage(indexName, 1, 10, sourceBuilder, builder);
        if(list.size()>0){
            dingdingRobot(indexName,list.size());
        }
    }

    public void dingdingRobot(String indexName, int size) {
        String url = "https://oapi.dingtalk.com/robot/send?access_token=bcd9e54764c2feb34db5af33f7146d846adbca1f35ce7e48d2da951dae31ac36";
        String requestJson = "" +
                "{\"msgtype\": \"text\",\"text\": {\"content\": \"warning 节点:"+indexName+"过去5分钟有错误警告"+size+"次,请及时查看\"}}";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
        String answer = restTemplate.postForObject(url, entity, String.class);
        System.out.println(answer);
    }



}
